package com.example.websocket.component;

import com.example.websocket.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class TestWebSocketComponent extends TextWebSocketHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("websocket 连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("websocket 接收到消息：" + message.toString());
        //向对端发送消息
        session.sendMessage(message);
        //获取HttpSession中的属性
        session.getAttributes().get("user");

        User user = objectMapper.readValue(message.asBytes(),User.class);

        User user = new User();
        user.setUserId(1);
        user.setUserName("zhangsan");
        String respJson = objectMapper.writeValueAsString(user);
        session.sendMessage(new TextMessage(respJson));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("websocket 连接异常：" + exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("websocket 断开连接");
    }
}
